import { app, BrowserWindow, ipcMain, Menu } from 'electron';
import { join } from 'path';

import IpcMessage from '../preload/preload';
import MainIpcService from './ipc//main-ipc-service';
import MainCommonService from './main-common-service';

const isDev = MainCommonService.isDevEnv;

function createWindow(): void {
  // Creates the browser window.
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      preload: join(__dirname, '../preload/preload.js'),
    },
  });

  const menu = Menu.buildFromTemplate([
    {
      label: 'File',
      submenu: [
        {
          click: () => {
            mainWindow.webContents.send(IpcMessage.updateCounter, 1);
          },
          label: 'Set1',
        },
        {
          click: () => mainWindow.webContents.send(IpcMessage.updateCounter, -1),
          label: 'Set-1',
        },
        {
          click: () => {
            const callbackMessageName = 'send-and-get-response';
            mainWindow.webContents.send(IpcMessage.sendAndGet, {
              payload: 'Msg from main',
              callbackMessageName: callbackMessageName,
            });
            ipcMain.once(callbackMessageName, (_, res): void =>
              console.log('Got result from renderer: ' + res),
            );
          },
          label: 'Send & Get',
        },
      ],
    },
  ]);

  Menu.setApplicationMenu(menu);

  // and load the index.html of the app.
  if (isDev) {
    // Loads local vue3 in dev mode.
    mainWindow.loadURL('http://localhost:5173');
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(join(__dirname, '../../index.html'));
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow();

  MainIpcService.setup();

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  MainIpcService.removeAllListeners();

  if (process.platform !== 'darwin') {
    app.quit();
  }
});
